package com.cuit.filter;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FilterChain {

    private List<Filter> filters = new ArrayList<>();

    private int index;

    public FilterChain() {
        this.index = 0;
    }

    public static FilterChain makeFilterChain(List<Filter> filters){
        FilterChain filterChain = new FilterChain();
        filterChain.addAll(filters);
        return filterChain;
    }

    public Filter next(){
        int nextIndex = index + 1;
        if (nextIndex >= filters.size()){
            log.error("当前过滤器已经是最后一个过滤器了");
            return null;
        }
        return filters.get(index+1);
    }

    public void addAll(List<Filter> filters){this.filters = filters;}

    public void doFilter(FilterContext fIlterContext) throws Exception {
        while (index < filters.size()){
            if (fIlterContext.isShouldBreak()){
                log.error("责任链提前关闭，请求信息如下[{}]", fIlterContext);
                break;
            }
            filters.get(index++).doFilter(fIlterContext);
        }
    }
}
